package com.swz.dcrm.ui.home;


import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.adpter.MultiItemTypeAdapter;
import com.swz.dcrm.adpter.VisitRecordAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.Clue;
import com.swz.dcrm.model.ClueRecord;
import com.swz.dcrm.model.MultipleChoice;
import com.swz.dcrm.model.PageResponse;
import com.swz.dcrm.model.PersonalInfo;
import com.swz.dcrm.model.VisitRecord;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;
import ezy.ui.view.RoundButton;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.CustomerManagementViewModel;
import com.swz.dcrm.ui.viewmodel.MainViewModel;
import com.swz.dcrm.ui.viewmodel.TodayPlanViewModel;
import com.swz.dcrm.util.CustomDecoration;
import com.swz.dcrm.util.DateUtils;
import com.swz.dcrm.widget.MultipleChoiceView;
import com.swz.dcrm.widget.StickyHeaderItemDecoration;
import com.swz.dcrm.widget.TimeLineItemDecoration;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.xh.baselibrary.callback.OnClickListener;
import com.xh.baselibrary.widget.BounceScrollView;


import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class ClueDetailFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_car_type)
    TextView tvCarType;
    @BindView(R.id.tv_next_visit)
    TextView tvNextVisit;
    @BindView(R.id.scroll)
    BounceScrollView scrollView;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_loan)
    TextView tvLoan;
    @BindView(R.id.tv_substitution)
    TextView tvSubstitution;
    @BindView(R.id.tv_state1)
    TextView tvState1;
    @BindView(R.id.tv_state2)
    TextView tvState2;
    @BindView(R.id.tv_state3)
    TextView tvState3;
    @BindView(R.id.tv_state4)
    TextView tvState4;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.btn_order_list)
    RoundButton btnOrderList;
    @BindView(R.id.btn_level)
    TextView level;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.btn_order)
    RoundButton btnOrder;
    @BindView(R.id.c_state)
    ConstraintLayout cState;
    private long clueId;
    private VisitRecordAdapter visitRecordAdapter;
    private Clue clue;
    ClueRecord clueRecord=new ClueRecord();

    private MultipleChoiceView<PersonalInfo> multipleChoiceView;
    @Inject
    TodayPlanViewModel todayPlanViewModel;
    @Inject
    MainViewModel mainViewModel;
    @Inject
    CustomerManagementViewModel customerManagementViewModel;
    private int page=1;
    private int size=15;
    private long total;

    public static ClueDetailFragment newInstance() {

        return new ClueDetailFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())) {
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }
        mHolder.showLoading();
        todayPlanViewModel.getClueDetail(clueId)
                .observe(this, pageBaseResponse -> {
                    if(pageBaseResponse==null){
                        return;
                    }
                   mHolder.showLoadSuccess();
                    if (pageBaseResponse.isSuccess() && pageBaseResponse.getData().getBsClueVO().getId() == clueId) {
                        clue=pageBaseResponse.getData().getBsClueVO();
                        clueRecord.setBsClueVO(clue);
                        if(clue.getDefeated()!=null&&clue.getDefeated()){
                            cState.setVisibility(View.GONE);

                        }else if((clue.getDefeated()==null||!clue.getDefeated())&&clue.getDeliveryCarTime()==null&&clue.getLatestOrderTime()!=null){
                            cState.setVisibility(View.VISIBLE);
                            btnOrderList.setVisibility(View.VISIBLE);
                            btnOrder.setVisibility(View.GONE);

                        }else {
                            cState.setVisibility(View.VISIBLE);
                            btnOrderList.setVisibility(View.GONE);
                            btnOrder.setVisibility(View.VISIBLE);
                        }
                        if(pageBaseResponse.getData().getBsClueRecordList()!=null&&pageBaseResponse.getData().getBsClueRecordList().size()>0){

                            clueRecord.setNextFollowType(pageBaseResponse.getData().getBsClueRecordList().get(0).getNextFollowType());
                            clueRecord.setNextFollowPurpose(pageBaseResponse.getData().getBsClueRecordList().get(0).getNextFollowPurpose());
                            clueRecord.setNextFollowTypeDesc(pageBaseResponse.getData().getBsClueRecordList().get(0).getNextFollowTypeDesc());
                            clueRecord.setNextFollowPurposeDesc(pageBaseResponse.getData().getBsClueRecordList().get(0).getNextFollowPurposeDesc());
                        }
                        if (rv.getItemDecorationCount() > 0) {
                            for (int i = 0; i < rv.getItemDecorationCount(); i++) {
                                rv.removeItemDecoration(rv.getItemDecorationAt(i));
                            }
                        }

                        if (clue.getFollowTimes() > 0) {
                            tvState1.setBackgroundResource(R.drawable.shape_circle_blue);
                        }
                        if (clue.getComeShopTimes() > 0) {
                            tvState2.setBackgroundResource(R.drawable.shape_circle_blue);
                        }
                        if (clue.getTestDriveTimes() > 0) {
                            tvState3.setBackgroundResource(R.drawable.shape_circle_blue);
                        }
                        if (clue.getQuotePriceTimes() > 0) {
                            tvState4.setBackgroundResource(R.drawable.shape_circle_blue);
                        }
                        switch (clue.getLevel()) {
                            case 1:
                                level.setBackgroundResource(R.drawable.shape_circle_red);
                                break;
                            case 2:
                                level.setBackgroundResource(R.drawable.shape_circle_orange);
                                break;
                            case 3:
                                level.setBackgroundResource(R.drawable.shape_circle_green);
                                break;
                            case 4:
                                level.setBackgroundResource(R.drawable.shape_circle_blue);
                                break;

                        }
                        if (clue.getLevelDesc() != null) {
                            level.setText(clue.getLevelDesc().substring(0, 1));
                        }
                        tvName.setText(clue.getCusName());
                        if(pageBaseResponse.getData().getBsClueRecordList()!=null&&pageBaseResponse.getData().getBsClueRecordList().size()>0){
                            tvNextVisit.setText(getString(R.string.item_next_visit,
                                    DateUtils.dateFormat(pageBaseResponse.getData().getBsClueRecordList().get(0).getNextFollowTime(),"yyyy-MM-dd"),
                                    pageBaseResponse.getData().getBsClueRecordList().get(0).getNextFollowTypeDesc()));
                        }
                        tvCarType.setText(clue.getIntentCar());
                        tvState1.setText(clue.getFollowTimes() + "");
                        tvState2.setText(clue.getComeShopTimes() + "");
                        tvState3.setText(clue.getTestDriveTimes() + "");
                        tvState4.setText(clue.getQuotePriceTimes() + "");
                        if (clue.getReplacementCar() || clue.getMortgage()) {
                            if (!clue.getMortgage()) {
                                tvLoan.setVisibility(View.GONE);
                            }
                            if (!clue.getReplacementCar()) {
                                tvSubstitution.setVisibility(View.GONE);
                            }
                        } else {
                            ll.setVisibility(View.GONE);
                            ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) tvCarType.getLayoutParams();
                            layoutParams.topToBottom = R.id.btn_level;
                            tvCarType.setLayoutParams(layoutParams);
                        }

                            tvSex.setText(clue.sexDesc());


                        visitRecordAdapter = new VisitRecordAdapter(getContext(), pageBaseResponse.getData().getBsClueRecordList());
                        visitRecordAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                                AddVisitRecordFragmentArgs.Builder builder=new AddVisitRecordFragmentArgs.Builder();
                                builder.setVisitRecord(new Gson().toJson(visitRecordAdapter.getDatas().get(position)));
                                go(null,R.id.action_clueDetailFragment_to_addVisitRecordFragment,builder.build().toBundle());
                            }

                            @Override
                            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                                return false;
                            }
                        });
                        StickyHeaderItemDecoration headersDecor = new StickyHeaderItemDecoration(visitRecordAdapter);
                        rv.addItemDecoration(headersDecor);
                        rv.setAdapter(visitRecordAdapter);

                    }
                });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_clue_detail;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        rv.setLayoutManager(new LinearLayoutManager(getContext()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        // rv.addItemDecoration(new CustomDecoration(getContext(),0,10,0,0));
        clueId =Long.valueOf( ClueDetailFragmentArgs.fromBundle(getArguments()).getClueId());
        scrollView.setOnScrollChangeListener((BounceScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (scrollY >= tvName.getBottom()) {
                title.setText(tvName.getText());
            } else {
                title.setText("");
            }
        });

        return true;
    }
    PopupMenu popupMenu;
    public void popMenu(){

        popupMenu=new PopupMenu(getContext(),ivMore);
        popupMenu.inflate(R.menu.menu);
        popupMenu.setOnDismissListener(menu -> ivMore.setImageResource(R.mipmap.more));
        popupMenu.setOnMenuItemClickListener(item -> {
            ivMore.setImageResource(R.mipmap.more_active);
            switch (item.getItemId()){
                case R.id.authorization:
                    if(multipleChoiceView!=null){

                        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                        lp.alpha = 0.4f;
                        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        getActivity().getWindow().setAttributes(lp);
                        multipleChoiceView.showAtLocation(getView(), Gravity.BOTTOM, 0, 0);
                    }else {
                        customerManagementViewModel.getSaleMan(page,size).observe(this,saleManObserver );
                    }

                    break;
                case R.id.defeated:
                    ReasonFragmentArgs.Builder builder3=new ReasonFragmentArgs.Builder();
                    builder3.setTitle(getString(R.string.clue_detail_defeated));
                    builder3.setClueId(String.valueOf(clue.getId()));
                    builder3.setTag(getString(R.string.clue_detail_reason,builder3.getTitle()));
                    go(null,R.id.action_clueDetailFragment_to_reasonFragment,builder3.build().toBundle());
                    break;

            }
            return false;
        });
        popupMenu.show();

    }
    Observer authorizedObserver= (Observer<BaseResponse<String>>) stringBaseResponse -> showToast(stringBaseResponse.getMsg());
    Observer saleManObserver =new Observer<PageResponse<PersonalInfo>>() {
        @Override
        public void onChanged(PageResponse<PersonalInfo> personalInfoPageResponse) {
            if(personalInfoPageResponse.isSuccess()){
                total=personalInfoPageResponse.getTotal();
            }
            if(personalInfoPageResponse.isSuccess()&&personalInfoPageResponse.getData().size()>0){

                if(multipleChoiceView==null){
                    List<MultipleChoice<PersonalInfo>> list=new ArrayList<>();
                    for (PersonalInfo personalInfo:personalInfoPageResponse.getData()){
                        MultipleChoice<PersonalInfo>multipleChoice=new MultipleChoice<>();
                        multipleChoice.setTag(personalInfo.getName());
                        multipleChoice.setT(personalInfo);
                        list.add(multipleChoice);
                    }
                    multipleChoiceView=new MultipleChoiceView<>(getContext(),"请选择授权销售人员",list,"确认授权");
                    multipleChoiceView.setOnClickListener(new OnClickListener<List<PersonalInfo>>() {
                        @Override
                        public void onItemClick(List<PersonalInfo> personalInfos) {

                            if(personalInfos.size()>0){
                                showNormalDialog(true, "提示",
                                        "是否确定授权" + personalInfos.get(0).getName() + "跟进此任务", new OnBtnClickL() {
                                            @Override
                                            public void onBtnClick() {
                                                customerManagementViewModel.authorized(clueId,personalInfos.get(0).getId()).observe(getViewLifecycleOwner(),
                                                        authorizedObserver);
                                                dismissDialog();
                                            }
                                        }, () -> {
                                            dismissDialog();

                                        });
                            }
                        }
                    });
                    multipleChoiceView.setOnLoadmoreListener(refreshlayout -> {
                        if(multipleChoiceView.getMultiItemTypeAdapter().getItemCount()<total){
                            page++;
                            customerManagementViewModel.getSaleMan(page,size).observe(getViewLifecycleOwner(),saleManObserver);
                        }
                    });
                    multipleChoiceView.setOnDismissListener(() -> {
                        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                        lp.alpha = 1f;
                        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        getActivity().getWindow().setAttributes(lp);
                    });
                    WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                    lp.alpha = 0.4f;
                    getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    getActivity().getWindow().setAttributes(lp);
                    multipleChoiceView.showAtLocation(getView(), Gravity.BOTTOM, 0, 0);

                }else {
                    List<MultipleChoice<PersonalInfo>> list=new ArrayList<>();
                    if(personalInfoPageResponse.getData().size()>0){
                        for (PersonalInfo personalInfo:personalInfoPageResponse.getData()){
                            MultipleChoice<PersonalInfo>multipleChoice=new MultipleChoice<>();
                            multipleChoice.setTag(personalInfo.getName());
                            multipleChoice.setT(personalInfo);
                            list.add(multipleChoice);
                        }
                    }
                    multipleChoiceView.refresh(personalInfoPageResponse.getPage(),list);
                }
            }
        }
    };
    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }

    @OnClick({R.id.btn_logging, R.id.iv_call, R.id.btn_order,R.id.btn_archives,R.id.btn_order_list,R.id.iv_more})
    public void btnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_logging:
                AddVisitRecordFragmentArgs.Builder builder = new AddVisitRecordFragmentArgs.Builder();
                builder.setClueRecord(new Gson().toJson(clueRecord));
                go(null, R.id.action_clueDetailFragment_to_addVisitRecordFragment, builder.build().toBundle());
                break;
            case R.id.iv_call:
                mainViewModel.getCall().setValue(clue.getCusPhone());
                break;
            case R.id.btn_order:
                AddOrderFragmentArgs.Builder builder2=new AddOrderFragmentArgs.Builder();
                builder2.setClue(new Gson().toJson(clue));
                go(null, R.id.action_clueDetailFragment_to_addOrderFragment, builder2.build().toBundle());
                break;
            case R.id.btn_archives:
                AddCustomerFragmentArgs.Builder builder1=new AddCustomerFragmentArgs.Builder();
                builder1.setClue(new Gson().toJson(clue));
                go(null,R.id.action_clueDetailFragment_to_addCustomerFragment,builder1.build().toBundle());
                break;
            case R.id.iv_more:
                popMenu();
                break;
            case R.id.btn_order_list:
                OrderFragmentArgs.Builder builder4=new OrderFragmentArgs.Builder();
                builder4.setClueId(new Gson().toJson(clue));
                go(null,R.id.action_clueDetailFragment_to_orderFragment,builder4.build().toBundle());
                break;
            /*
            case R.id.btn_cancel_order:
                ReasonFragmentArgs.Builder builder4=new ReasonFragmentArgs.Builder();
                builder4.setTitle(getString(R.string.clue_detail_cancel_order));
                builder4.setClueId(String.valueOf(clue.getId()));
                builder4.setTag(getString(R.string.clue_detail_reason,builder4.getTitle()));
                go(null,R.id.action_clueDetailFragment_to_reasonFragment,builder4.build().toBundle());
                break;*/
         /*   case R.id.btn_confirm:
                showNormalDialog(false, "", "是否确定交车", () -> {

                    dismissDialog();
                }, () -> {
                    dismissDialog();
                });*/

        }
    }





}
